import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import { getEnv } from './env'

const env = getEnv()
// axios配置
const config = {
  // 接口请求的地址
  baseURL: env.VITE_WEB_BASE_API,
  // 发布环境下 无法获取env 暂时写死 发布后测试接口调用成功
  // baseURL: '/dev-api',
  timeout: 10000,
};
// 返回值类型
export interface Result<T = any> {
  code: number;
  msg: string;
  data: T;
}
// 只有请求封装用的Yu，方便简写
class Yu {
  private instance: AxiosInstance;
  // 初始化
  constructor(config: AxiosRequestConfig) {
    // 实例化axios
    this.instance = axios.create(config);
  }
  
  // Get请求
  get<T = Result>(url: string, params?: object): Promise<T> {
    return this.instance.get(url, { params });
  }
  // Post请求
  post<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.post(url, data);
  }
  // Put请求
  put<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.put(url, data);
  }
  // Delete请求  /yu/role/1
  delete<T = Result>(url: string, params?: any): Promise<T> {
    return this.instance.delete(url, { params });
  }
  // 图片上传
  upload<T = Result>(url: string, params?: object): Promise<T> {
    return this.instance.post(url, params, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  }
}
export default new Yu(config);
